
package com.djx.comm.util;


import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


/**
 * @ClassName AESUtils
 * @description AES加解密工具类
 * @Author: dingjunxiong
 * @Time ：2020年04月07日
 */
public class AesUtils {
    /**
     * aes key
     */
    private static String SALT = "1gqaz@SX#EDC4rfv";
    private static String algorithm = "AES";


    /**
     * 加密
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String str) throws Exception {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(SALT.getBytes("utf-8"), algorithm));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return new BASE64Encoder().encode(bytes);
    }

    /**
     * 解密
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String str) throws Exception {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE,
                new SecretKeySpec(SALT.getBytes("utf-8"), algorithm));
        byte[] bytes = new BASE64Decoder().decodeBuffer(str);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }


    public static void main(String[] args) {
        try {
            String cipherText = AesUtils.aesEncrypt("abcdefg");
            System.out.println("密文：" + cipherText + "长度：" + cipherText.length());
            String clearText = AesUtils.aesDecrypt(cipherText);
            System.out.println("明文：" + clearText + "长度：" + clearText.length());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}